	<?php
	// no direct access
	defined( '_VALID_MOS' ) or die( 'Restricted access' );
  global $thisMVersion, $noSupportReason, $mosConfig_absolute_path, $buildLevel, $opt;
?>

<?php

	ob_start();

	error_reporting(E_ALL);
	ini_set('memory_limit', '16M');
	ini_set('max_execution_time', '120');

		if (file_exists( '../includes/version.php' )) {
			$_VERSION 	   = new version();
		} 
		$thisMName     		=	$_VERSION->CODENAME;
		$thisMDev			=	$_VERSION->DEV_STATUS;
		$thisMRDate			=	$_VERSION->RELDATE;
		$thisFullMVersion	=	$_VERSION->PRODUCT .' '. $_VERSION->RELEASE .'.'. $_VERSION->DEV_LEVEL .' '. $_VERSION->DEV_STATUS .' [ '.$_VERSION->CODENAME .' ] '. $_VERSION->RELDATE;


		// Supported M Releases
		if (($thisMName == "Zeppy") && ($thisMDev == "Stable")) {
			$thisMVersion = '4.6.2';
		} else { 
								// Un-Supported M Releases

									if ($thisMDev != "Stable") {
										$noSupportReason .= "Your Mambo version is either not a Stable version or is a nightly build/SVN Release.";
									} 

									$supportedVersions = "<br />Mambo Tools Suite supports the following Mambo versions only;<br /><br /> - 4.6.2<br />";
									$thisMVersion = 'Sorry but this Mambo Version is not supported by Mambo Tools Suite...'; 
									echo "<br /><br /><div align='center'><div align='center' class='msg-warn' style='text-align: left; width: 75%; min-width: 75%'><b>Discovered Mambo Version :</b> ". $thisFullMVersion ."";
//									echo "<br /><b>Release :</b> ". $thisJDev .", ". $thisJRDate ."";
									echo "<br /><br /><b>Reason :</b><br />". $noSupportReason ."";
									echo "<br /><br /><b>Supported Versions :</b> ". $supportedVersions ."";
									echo "</div></div><br /><br />";


									$tabs->endTab();
									$tabs->endPane();
									exit;
									}

	echo "<div class='' style='text-align: left;'><b>Discovered Mambo Version :</b> ". $thisFullMVersion ."<br /><b>Release :</b> ". $thisMVersion ."";
	echo "</div><br />";

	$task = '';
		if ( isset($_GET['task']) ) {
			$task = $_GET['task'];
		}

	$skipfiles = array(
	  'installation/*'
	);
?>
		
		

<?php


	switch($task){
	  case 'generate':
	    generateMd5Hash($mosConfig_absolute_path);
	    break;
	  default:
	    compair();
	    break;
	}
  

function compair(){
	global $thisMVersion, $thisFullMVersion, $mosConfig_absolute_path;

	$path = $mosConfig_absolute_path ."/";
	$path = str_replace('\\', '/', $path);
	$path = str_replace('//', '/', $path);


	ob_flush();
	flush();
?>

  <div class="data-container" style="padding: 4px; margin-top: 5px; margin-bottom: 5px;"><strong>Compare File Hashes Against Original Distribution</strong></div>

<?php
	$orig = array();
	$orig_c = file($path ."administrator/components/com_mts/m_" . $thisMVersion . ".txt");

		for($i=0,$n=count($orig_c);$i<$n;$i++){
			$line = explode("\t", $orig_c[$i]);
		    $orig[$path . $line[0]] = trim($line[1]);
		}

//  Debug only
//  echo '<pre>';
//  print_r($orig);
//  echo '</pre>';
  ?>
  
  <table border="0" width="100%">
  <tr>
    <th width="100">Severity</th>
    <th>Filename</th>
    <th width='350">Type</th>
  </tr>

  <?php

  ob_flush();
  flush();

	$dirs = array('administrator', 'cache', 'components', 'editor', 'help', 'images', 'includes', 'language', 'mambots', 'media', 'modules', 'templates', 'uploadfiles', 'parameters', 'files');


	$files = jtsmosReadDirectory($path, '.', false, true);
		for($i=0,$n=count($dirs);$i<$n;$i++){
			$dir = $dirs[$i];
			$tmp = jtsmosReadDirectory($path . $dir, '.', true, true);    
		    $files = array_merge($files, $tmp);
		}

//  Debug Only
//  echo '<pre>';
//  print_r($files);
//  print_r($orig);
//  echo '</pre>';
//  die;

	for($i=0,$n=count($files);$i<$n;$i++){
		$file = str_replace('\\', '/', $files[$i]);

	if($content = @file_get_contents($file)){ //check if file is file or directory

		if((!empty($orig[$file])) && (getFileHash($file) != $orig[$file])){ //when a hash exists
			echo '<tr><td style="border: 1px solid #F57900; border-left: 6px solid #F57900; background-color: #fffacd; padding-left: 20px; background-image: url(components/com_jts/images/warn_icon_20px.png); background-position: 0px 0px; background-repeat: no-repeat; overflow: auto; height: 12px width: 12px;">WARNING</td><td class="left-col">' . $file . '</td><td class="left-col">File is corrupted or has been altered</td></tr>';
		}

		ob_flush();
		flush();

		//check other things
		$type = explode('.', $file);
		if((!preg_match('#_VALID_MOS#', $content) && !preg_match('#_JEXEC#', $content)) && ($type[sizeof($type) - 1] == 'php')){
		//actually, we should do a few more checks.. a class or switch file is safe anyhow

        if(!preg_match('#<?php#', $content)){ //file does not contain php, ignore
			unset($orig[$file]);
			continue;
        }

        //check if file contains includes with variables in it
        if(
          !preg_match('#require(\s)?\((.*)?\$(.*)?\)#', $content) &&
          !preg_match('#require_once(\s)?\((.*)?\$(.*)?\)#', $content) &&
          !preg_match('#include(\s)?\((.*)?\$(.*)?\)#', $content) &&
          !preg_match('#include_once(\s)?\((.*)?\$(.*)?\)#', $content)
        ){
          //if not, skip this one as well
          unset($orig[$file]);
          continue;
        }
        
        echo '<tr><td style="border: 1px solid #4B0082; border-left: 6px solid #4B0082; background-color: #e6e6fa; padding-left: 20px; background-image: url(components/com_jts/images/advisor_icon_20px.png); background-position: 0px 0px; background-repeat: no-repeat; overflow: auto; height: 12px width: 12px;">SECURITY</td><td class="left-col" >' . $file . '</td><td class="left-col">File does not contain _VALID_MOS OR _JEXEC.</td></tr>';
      }
    }
    
    unset($orig[$file]);
  }
?>
</table>
<div style="font-size: 9px; color: #C0C0C0;">
<br /><br />
Adapted from <a href="http://www.joomla-addons.org">Adam van Dongen</a> - <a href="http://www.joomla-addons.org/joomla-diagnostics.html">Joomla Diagnostics</a><br />
</div>

<?php 
	$width 	= 400;	// width of 100%
	$tabs 	= new mosTabs(0);

	$tabs->endTab();
	$tabs->startTab("Missing Files","missing");

		echo '<nobr clear="all">';
		echo '<table border="0" cellspacing="2" cellpadding="2" id="jts-container" class="adminform">';
		echo '<tr>';
		echo '<th colspan="3">Missing Core Files</th>';
		echo '</tr>';
		echo '</table>';

?>
    <br />
    <div class="data-container" style="padding: 4px; margin-top: 5px; margin-bottom: 5px;"><strong>Missing Files From Distribution</strong></div>
    <table border="0" width="100%">
    <tr>
      <th width="100">Severity</th>
      <th>Filename</th>
      <th width="350">Type</th>
    </tr>

<?php
	if(sizeof($orig) > 0){ 

    $keys = array_keys($orig);
		for($i=0,$n=count($keys);$i<$n;$i++){
		$file = $keys[$i];
			echo '<tr><td style="border: 1px solid #DC143C; border-left: 6px solid #DC143C; background-color: #FFFF00; padding-left: 20px; background-image: url(components/com_jts/images/error_icon_20px.png); background-position: 0px 0px; background-repeat: no-repeat; overflow: auto; height: 12px width: 12px;">MISSING</td><td class="left-col">' . $file . '</td><td class="left-col">File is missing</td></tr>';

			ob_flush();
			flush();
		}

	} else { 
		echo '<tr><td colspan="3" style="border: 1px solid #32A500; border-left: 6px solid #32A500; background-color: #f0f8ff; padding-left: 20px; background-image: url(components/com_jts/images/good_icon_20px.png); background-position: 0px 0px; background-repeat: no-repeat; overflow: auto; height: 12px width: 12px;">No Missing Files.</td></tr>'; 
	}

} 

?>

</table>

<div style="font-size: 9px; color: #C0C0C0;">
<br /><br />
Adapted from <a href="http://www.joomla-addons.org">Adam van Dongen</a> - <a href="http://www.joomla-addons.org/joomla-diagnostics.html">Joomla Diagnostics</a><br />
</div>

<?php
ob_end_flush();

function getFileHash($file){
  $content = file_get_contents($file);
  $content = str_replace(array("\n", "\r"), "", $content);

  return md5($content);
}

function generateMd5Hash($opath = null){
  global $mosConfig_absolute_path, $thisJVersion, $skipfiles, $isV15;

  if(is_null($opath)){
    return;
  }


  $files = jtsmosReadDirectory($opath, '.', true, true);

  $filecontent = '';

  for($i=0,$n=count($files);$i<$n;$i++){

    $skip = false;

    $file = str_replace($opath . '/', '', str_replace("\\", "/", $files[$i]));
    echo $file . '<br />';
    if(in_array($file, $skipfiles)){
      $skip = true; //skip files that have been defined...
    }
    for($j=0,$k=count($skipfiles);$j<$k;$j++){
      $skipfile = $skipfiles[$j];
      
      if(strpos($skipfile, '*')){//file contains * sign
        $skipfile = str_replace('*', '', $skipfile);
        
        if(substr($file, 0, strlen($skipfile)) == $skipfile){
          $skip = true;
        }
      }
    }
    
    if($skip){
      continue;
    }
    
    if(is_file($opath . '/' . $file)){
      $filecontent .= $file . "\t" . getFileHash($opath . '/' . $file) . "\n";
    }
  }
  
  $fp = fopen("components/com_mts/m_mysite.txt", "w");
  fwrite($fp, $filecontent);
  fclose($fp);
}



/** Functions Modified For Use With MTS **/
/**
* Utility function to read the files in a directory
* @param string The file system path
* @param string A filter for the names
* @param boolean Recurse search into sub-directories
* @param boolean True if to prepend the full path to the file name
*/

function jtsmosReadDirectory( $path, $filter='.', $recurse=false, $fullpath=false  ) {
	$arr = array();
	if (!@is_dir( $path )) {
		return $arr;
	}
	$handle = opendir( $path );

	while ($file = readdir($handle)) {
		$dir = jtsmosPathName( $path.'/'.$file, false );
		$isDir = is_dir( $dir );
		if (($file != ".") && ($file != "..")) {
			if (preg_match( "/$filter/", $file )) {
				if ($fullpath) {
					$arr[] = trim( jtsmosPathName( $path.'/'.$file, false ) );
				} else {
					$arr[] = trim( $file );
				}
			}
			if ($recurse && $isDir) {
				$arr2 = jtsmosReadDirectory( $dir, $filter, $recurse, $fullpath );
				$arr = array_merge( $arr, $arr2 );
			}
		}
	}
	closedir($handle);
	asort($arr);
	return $arr;
}


/**
* Function to strip additional / or \ in a path name
* @param string The path
* @param boolean Add trailing slash
*/

function jtsmosPathName($p_path,$p_addtrailingslash = true) {
	$retval = "";

	$isWin = (substr(PHP_OS, 0, 3) == 'WIN');

	if ($isWin)	{
		$retval = str_replace( '/', '\\', $p_path );
		if ($p_addtrailingslash) {
			if (substr( $retval, -1 ) != '\\') {
				$retval .= '\\';
			}
		}
		// Remove double \\
		$retval = str_replace( '\\\\', '\\', $retval );
	} else {
		$retval = str_replace( '\\', '/', $p_path );
		if ($p_addtrailingslash) {
			if (substr( $retval, -1 ) != '/') {
				$retval .= '/';
			}
		}
		// Remove double //
		$retval = str_replace('//','/',$retval);
	}

	return $retval;
}
?>



<?php
		$tabs->endTab();
		$tabs->endPane();
?>		